<!DOCTYPE html>
<html lang="en-US" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>用户管理</title>

<link rel="stylesheet" th:href="@{~/component/layui/css/layui.css}" media="all">
<link rel="stylesheet" th:href="@{~/component/pear/css/pear-module/dtree/dtree.css}" media="all">
<link rel="stylesheet" th:href="@{~/component/pear/css/pear-module/dtree/font/dtreefont.css}" media="all">
<link rel="stylesheet" th:href="@{~/component/pear/css/pear-module/button.css}" media="all">
<link rel="stylesheet" th:href="@{~/common/css/common.css}" media="all">


</head>
<body style="overflow-y: hidden;">
	<div class="my-header ">
		<div >
			<form class="layui-form layui-inline" name="searchForm">
				<div class="layui-input-inline">
				  <input type="text" name="username"  autocomplete="off" placeholder="请输入用户账号" class="layui-input">
				</div>
				<div class="layui-input-inline">
				  <input type="text" name="nickname"  autocomplete="off" placeholder="请输入用户名称" class="layui-input">
				</div>
				<div class="layui-input-inline">
				  <input type="text" name="phone"  autocomplete="off" placeholder="请输入用户手机" class="layui-input">
				</div>
				<div class="layui-input-inline">
					<ul id="deptTree"  class="dtree" data-id="0"></ul>
				</div>
				<!-- <div class="layui-input-inline">
				  <select name="sex">
			        <option value="">请选择性别</option>
			        <option value="1">男</option>
			        <option value="0">女</option>
			      </select>
				</div> -->
				<div class="layui-input-inline">
				  <select name="status">
			        <option value="">请选择账号状态</option>
			        <option value="1">正常</option>
			        <option value="0">禁用</option>
			      </select>
				</div>
			
				<div style="margin-top: 16px;">
					<div class="layui-inline">
						<button sec:authorize="hasAuthority('sys:user:select')" type="button" class="pear-btn pear-btn-success" lay-submit lay-filter="search"><i class="layui-icon layui-icon-search"></i> 查询</button>
					</div>
					<div class="layui-inline">
						<button sec:authorize="hasAuthority('sys:user:select')" type="button" onclick="window.formReset(searchForm)" class="pear-btn pear-btn-warming" ><i class="layui-icon layui-icon-refresh"></i> 重置</button>
					</div>
					<div class="layui-inline">
						<button sec:authorize="hasAuthority('sys:user:insert')" type="button" class="pear-btn pear-btn-primary" id="add"><i class="layui-icon layui-icon-addition"></i> 新增 </button>
					</div>
					<div class="layui-inline">
						<button sec:authorize="hasAuthority('sys:user:delete')"  type="button" class="pear-btn pear-btn-danger" id="batchDelete" ><i class="layui-icon layui-icon-delete"></i> 批量删除 </button>
					</div>
				</div>
			</form>
		</div>
	</div>

<!-- 列表表格数据 -->
<table class="my-table" id="user-table" lay-filter="user-table"></table>

<!-- 列表工具：编辑、删除 -->
<script type="text/html" id="user-bar">
	<button sec:authorize="hasAuthority('sys:user:update')" class="pear-btn pear-btn-primary pear-btn-sm" lay-event="edit" title="编辑"><i class="layui-icon layui-icon-edit"></i></button>
	<button sec:authorize="hasAuthority('sys:user:delete')" class="pear-btn pear-btn-danger pear-btn-sm" lay-event="delete" title="删除"><i class="layui-icon layui-icon-delete"></i></button>
</script>

<!-- 列表性别转义：0-女，1-男 -->
<script type="text/html" id="user-sex">
	{{ d.sex==1 ? '<span>男</span>': d.sex==0 ? '<span>女</span>' : '未知' }} 
</script>

<!-- 角色列 -->
<!-- <script type="text/html" id="user-role">
	{{ d.roleList }} 
</script> -->

<!-- 列表账号状态开关：0-禁用，1-正常 -->
<script type="text/html" id="user-status">
	<input type="checkbox" name="{{d.id}}" value="{{d.status}}"  lay-skin="switch" lay-text="正常|禁用" lay-filter="user-status"  {{ d.status == 1 ? 'checked' : '' }}>
</script>

<script th:src="@{~/component/layui/layui.js}" charset="utf-8"></script>
<script th:src="@{~/component/pear/pear.js}" charset="utf-8"></script>
<script th:src="@{~/common/js/jquery-1.11.2.min.js}" charset="utf-8"></script>

<script type="text/javascript">
	
layui.use(['form', 'layedit', 'laydate','element','table','dtree'], function(){
	var $ = layui.jquery
	  ,form = layui.form
	  ,layer = layui.layer
	  ,laypage = layui.laypage
	  ,table = layui.table
	  ,dtree = layui.dtree;
	
	/* 表格渲染 */
	table.render({
	  elem: '#user-table' //指定原始表格元素选择器（推荐id选择器）
	  ,url: '/user/list'
	  ,toolbar:true
	  ,defaultToolbar: ['filter']
	  ,parseData: function(res){ //res 即为原始返回的数据
	  		if(res.code != 0){
	  			layer.msg(res.msg,{icon:2,time:2000});
	  			return;
	  		}
		    return {
		      "code": res.code, //解析接口状态
		      "msg": res.msg, //解析提示文本
		      "count": res.data.total, //解析数据长度
		      "data": res.data.list //解析数据列表
		    };
	   }
	  
	  ,page: true
	  ,height: 'full-188' //容器高度
	  ,cols: [ [ 
		  	{checkbox: true}
		    ,{type: 'numbers', title: '序号', width: 80, align: 'center'}
		    ,{field: 'username', title: '用户账号', align: 'center', }
		    ,{field: 'nickname', title: '用户名称', align: 'center'}
		    ,{field: 'sex', title: '用户性别', align: 'center', templet: '#user-sex'}
		    ,{field: 'phone', title: '用户手机', align: 'center',}
		    ,{field: 'deptName', title: '所属部门', align: 'center',}
		    //,{field: 'roleList', title: '角色', align: 'center'}
		    ,{field: 'status', title: '账号状态', align: 'center', templet: '#user-status'}
		    ,{field: 'createTime', title: '注册时间', align: 'center',width:180}
		    ,{toolbar: '#user-bar', title: '操作', minWidth: 160,  align: 'center'}
	  ] ]
	  
	});
	
	/* 重写了form表单的reset重置事件，解决type='reset'的写法无法重置部门树形结构下拉框问题 */
	window.formReset = function(form){
		form.reset();
		$("input[type='hidden'][name='deptId']").val("");
		$("input[type='hidden'][name='deptName']").val("");
	}
	
	/* 工具条上的事件 */
	table.on('toolbar(user-table)', function(obj) {
		if (obj.event === 'refresh') {
			window.refresh();
		}
	});
	
	/* 列表中的工具上的按钮事件 */
	table.on('tool(user-table)', function(obj) {
		if (obj.event === 'delete') {
			window.delete(obj);
		} else if (obj.event === 'edit') {
			window.edit(obj);
		}
	});
	
	/* 点击查询按钮 */
	form.on('submit(search)', function(data) {
		table.reload('user-table', {
			where: data.field
		})
		return false;
	});
	
	
	/* 账号状态开关事件 */
	form.on('switch(user-status)', function(obj) {
		var status = obj.elem.checked ? '1' : '0';
		var id = obj.elem.name;
		var data = {"id":id,"status":status}
		
		$.ajax({
            url:"/user/updateStatus",
            data:JSON.stringify(data),
            contentType:'application/json',
            type:'post',
            success:function(result){
                if(result.code == 0){
                    layer.msg(result.msg,{icon:1,time:1000});
                }else{
                    layer.msg(result.msg,{icon:2,time:2000},function(){window.refresh();});
                }
            }
        })
	});
	
	/* 渲染部门树形选择框 */
    dtree.render({
        elem: "#deptTree",
        initLevel: "1",
        method: 'get',
        selectTips: "请选择部门",
        ficon: ["1", "-1"],
        icon:"2",
        selectInputName: {
          nodeId: "deptId",
          context: "deptName"
        },
        dataStyle: "layuiStyle",
        url: "/dept/selectDeptTree",
        response:{message:"msg",statusCode:0},
        select: true
    });
	
	/* 刷新table */
    window.refresh = function(param) {
		table.reload('user-table');
	}
	
    /* 点击编辑，弹出编辑页面 */
    window.edit = function(obj) {
    	if(obj.data.id == 1){
    		layer.msg('禁止编辑超级管理员【admin】',{icon:2,time:3000});
    		return false;
    	}
		layer.open({
			type: 2,
			title: '修改用户信息',
			shade: 0.1,
			area: ['500px', '520px'],
			content: '/user-edit?id='+obj.data.id
		});
	}
    
    /* 点击删除，删除用户 */
    window.delete = function(obj) {
    	if(obj.data.id == 1){
    		layer.msg('禁止删除超级管理员【admin】',{icon:2,time:3000});
    		return false;
    	}
		layer.confirm('确定要删除该用户【'+obj.data.nickname+'】', {
			icon: 3,
			title: '提示'
		}, function(index) {
			layer.close(index,{time: 5*1000});
			let loading = layer.load();
			let id = obj.data.id;
			$.post("/user/delete",{"id":id},function(result){
				layer.close(loading);
                if(result.code == 0){
                	layer.msg(result.msg, {
						icon: 1,
						time: 1000
					}, function() {
						obj.del();
					});
                }else{
                    layer.msg(result.msg,{icon:2,time:3000});
                }
			});
		});
	}
    
    /* 点击批量删除，删除用户 */
    window.batchDelete = function(obj) {
    	var tableData = table.checkStatus("user-table");
		var data = tableData.data;
		if (data.length === 0) {
			layer.msg("未选中数据", {
				icon: 3,
				time: 1000
			});
			return false;
		}
		let idList = [];
		for (let i = 0; i < data.length; i++) {
			if(data[i].id == 1){
	    		layer.msg('禁止删除超级管理员【admin】',{icon:2,time:3000});
	    		return false;
	    	}
			idList.push(data[i].id);
		}
		
		layer.confirm('确定要删除选中的【'+data.length+'】条数据', {
			icon: 3,
			title: '提示'
		}, function(index) {
			layer.close(index);
			let loading = layer.load();
			$.ajax({
				url: "/user/batchDelete",
				data:JSON.stringify(idList),
				contentType:"application/json",
				type: 'post',
				success: function(result) {
					layer.close(loading);
					if (result.code == 0) {
						layer.msg(result.msg, {
							icon: 1,
							time: 1000
						}, function() {
							table.reload('user-table');
						});
					} else {
						layer.msg(result.msg, {
							icon: 2,
							time: 2000
						});
					}
				}
			})
		});
	}
	
})

/* 点击新增按钮，弹出新增页面 */
$("#add").click(function(){
	layer.open({
		type: 2,
		title: '新增用户',
		shade: 0.1,
		area: ['500px', '520px'],
		content: '/user-add'
	});
});

/* 点击批量删除 */
$("#batchDelete").click(function(){
	window.batchDelete();
});

</script>

</body>
</html>